package com.qf.config;

import com.qf.dao.PermissionRepository;
import com.qf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Description: 公用常量
 * @Data: 2022/9/15 18:23
 * @Pacakge: com.qf.config
 * @ClassName: MyIntercept
 * @Author: fan
 * 拦截器
 */
@Component
public class MyIntercept implements HandlerInterceptor {
    @Autowired
    PermissionRepository permissionRepository;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session中的对象
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user == null){
            response.sendRedirect("/user/index");
            return false;
        }
        //2.将从域中获取的数据进行数据类型转换
        User username = (User) user;
        //3.通过username查询出所对应的权限
        List<String> permission = permissionRepository.findPermissionByUsername(username.getUsername());
        //4.从request域中获取请求地址
        String requestURI = request.getRequestURI();
        //5.通过list集合进行判断,如果包含请求地址则放行,否则拦截
        if (!permission.contains(requestURI)){
            //6.展示没有权限的页面提示用户
            response.setContentType("application/json");
            //解决中文乱码
            response.setCharacterEncoding("utf-8");
            //响应提示信息
            PrintWriter writer = response.getWriter();
            writer.write("您没有该权利,请找管理员申请");
            return false;
        }
        return true;
    }

}
